package com.lims.algorithm.algset.a_other;

//螺旋打印矩阵
public class SpiralMatrix {
    public static int[][] createMatrix(int n){
        int[][] matrix = new int[n][n];
        int right = 1, down = 2, left = 3, up = 4;
        int direction = right;

        int numb = n * n;
        int i = 0, j = 0;
        for (int p = 1; p <= numb; p++){
            matrix[i][j] = p;

            if (direction == right){
                if (j + 1 < n && matrix[i][j + 1] == 0){
                    j++;
                }else {
                    i++;
                    direction = down;
                    continue;
                }
            }
            if (direction == down){
                if (i + 1 < n && matrix[i+1][j] == 0){
                    i++;
                }else {
                    j--;
                    direction = left;
                    continue;
                }
            }
            if (direction == left){
                if (j - 1 >= 0 && matrix[i][j-1] == 0){
                    j--;
                }else {
                    i--;
                    direction = up;
                    continue;
                }
            }
            if (direction == up){
                if (i - 1 >= 0 && matrix[i-1][j] == 0){
                    i--;
                }else {
                    j++;
                    direction = right;
                    continue;
                }
            }
        }
        return matrix;
    }

    public static void main(String[] args) {
        int[][] n = createMatrix(6);
        for (int i=0;i<n.length;i++){
            for (int j=0;j<n[i].length;j++){
                System.out.print(n[i][j] + " ");
            }
            System.out.println("");
        }
    }
}
